import requests
import time
import json
import hashlib
from urllib import parse
import pandas as pd


def get_location_info(address_str):
    # 以get请求为例http://api.map.baidu.com/geocoder/v2/?address=百度大厦&output=json&ak=你的ak
    queryStr = '/geocoding/v3/?address=%s&output=json&ak=GRjP1nuygNMvCckIQjKTcm7oi596zHaa' % address_str
    # 对queryStr进行转码，safe内的保留字符不转换
    encodedStr = parse.quote(queryStr, safe="/:=&?#+!$,;'@()*[]")
    # 在最后直接追加上sk
    rawStr = encodedStr + '8RKjx25ZP1g4pYQq98sqKGlHvg4DlEZT'
    # 计算sn
    sn = (hashlib.md5(parse.quote_plus(rawStr).encode("utf8")).hexdigest())
    # 由于URL里面含有中文，所以需要用parse.quote进行处理，然后返回最终可调用的url
    url = parse.quote("http://api.map.baidu.com" + queryStr + "&sn=" + sn, safe="/:=&?#+!$,;'@()*[]")
    res = requests.get(url, headers={"content-type": "application/json"})
    time.sleep(0.5)
    return res.content.decode()


def handle_location_info(json_data):
    data = json.loads(json_data)
    result = data.get('result', {})
    location_info = result.get('location', {})
    location = f"{location_info.get('lng', '')},{location_info.get('lat', '')}"
    return location


def main():
    df = pd.read_csv('../static/data/scenic_spots_info_clean.csv')
    df['location'] = df['地址'].apply(lambda x: handle_location_info(get_location_info(x)))
    df.to_csv('../static/data/scenic_spots_info_clean_with_location.csv', index=False)


if __name__ == '__main__':
    main()